package com.red.security;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.red.entity.Account;
import com.red.entity.Perm;
import com.red.entity.Role;
import com.red.entity.RolePerm;
import com.red.mapper.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {
    @Autowired
    private AccountMapper accountMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;
    @Autowired
    private PermMapper permMapper;
    @Autowired
    private RolePermMapper rolePermMapper;

    @Override
    public UserDetails loadUserByUsername(String phone) throws UsernameNotFoundException {
        Account account = accountMapper.selectOne(
                new QueryWrapper<Account>().eq("phone",phone)
        );
        if(account == null){
            throw new UsernameNotFoundException(phone);
        }
        List<Integer> roleIds = userRoleMapper.selectRoleIdsByAccountId(account.getId());
        //通过角色ID集合查询角色集合
        List<Role> roles = roleMapper.selectBatchIds(roleIds);
        //角色集合封装成List<GrantedAuthority>
        List<GrantedAuthority> authorities = new ArrayList();
        if(roles != null){
        for (Role role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        }
        //通过角色ID集合查询权限集合
        List<Integer> permIds = rolePermMapper.selectPermIds(
                new QueryWrapper<RolePerm>().in("role_id", roleIds)
        );
        //通过权限ID集合查询权限集合
        List<Perm> perms = permMapper.selectBatchIds(permIds);
        if(perms != null){
        for (Perm perm : perms) {
            authorities.add(new SimpleGrantedAuthority(perm.getPermCode()));
        }
        }
        return new User(account.getPhone(),account.getPassword(), authorities);
    }
}
